<template>
    <div class="page">
        <Header title="京潮计划" left-arrow />
        <div class="content">
            <div class="card">
                <div class="title">
                    您要投放的城市
                </div>
                <tags-list :data="City" :selection-data="selectCity" @click="handleClick"></tags-list>
                <div class="city-label">
                    已选：
                    <span class="city-sel">{{ formatCity(formData.city) }}</span>
                </div>
            </div>
            <div class="card">
                <div class="title">
                    您的目标人群标签
                </div>
                <div class="title-bs">
                    电商行为标签
                </div>
                <MyCell label="选择类目" placeholder="请选择" :value="formatCategory(formData.categoryList)" @click="pickCategory"></MyCell>
                <MyCell v-show="formData.categoryList.length" label="行为类型" placeholder="请选择" :value="formData.action" @click="pickType"></MyCell>
                <MyCell v-show="formData.categoryList.length" label="时间范围" placeholder="请选择" :value="formData.time" @click="pickTime"></MyCell>
                <div class="title-sm">
                    人口属性标签
                </div>
                <template v-for="(item, index) in personList" :key="index">
                    <tags-list :title="item.name" :is-multiple="true" :show-limit="true" :data="(item.children as unknown as [])" label="name" value="id" :selection-data="form[index]" @click="handleClick($event, index)" />
                </template>
            </div>
        </div>
        <footer class="footer">
            <Button type="primary" block @click="next">
                下一步
            </Button>
            <div class="van-safe-area-bottom"></div>
        </footer>
        <!-- 城市选择 -->
        <city-area-selecter
            :show="showCityPicker"
            :list="selectList"
            :type="selectType"
            :selected="formData.checkedCityData"
            @close="showCityPicker = false"
            @confirm="onCityConfirm"
        />
        <!-- 品类选择 -->
        <city-area-selecter
            :show="showCategoryPicker"
            :list="selectList"
            :type="selectType"
            :selected="formData.checkedCategoryData"
            :is-require="false"
            @close="showCategoryPicker = false"
            @confirm="onCategoryConfirm"
        />
        <Picker title="行为类型" :is-show="showTypePicker" :columns="typeColumns" @close="showTypePicker = false" @confirm="typeConfirm"></Picker>
        <Picker title="时间范围" :is-show="showTimePicker" :columns="timeColumns" @close="showTimePicker = false" @confirm="timeConfirm"></Picker>
    </div>
</template>

<script name="productsJd" lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { store } from '@/store';
import { Button, Toast } from 'vant';
import { City } from './consts';
import { TreeChildModel, ReturnData } from '@/components/CityAreaSelecter/city.module';
import { getJcTopTags, getJcChildTags, topTagModel, checkTagData } from '@/api/jd';
import tagsList from '@/components/tagsList.vue';
import Picker from '@/components/DurationSelecter/index.vue';
import Header from '@/components/Header/index.vue';
import CityAreaSelecter from '@/components/CityAreaSelecter/index.vue';
import MyCell from '@/components/MyCell/index.vue';
import _ from 'lodash';
import { clearLoading, showLoading } from '@/api';

const router = useRouter();

const showCityPicker = ref<boolean>(false);
const showCategoryPicker = ref<boolean>(false);
const showTypePicker = ref(false);
const showTimePicker = ref(false);

interface Tag{
    [key: string]: string | number,
    label: string,
}

interface Form{
    [key: string]: Tag[]
}

const selectCity = ref([
    {
        label: '按省市',
        value: '1',
    }
]);

const form = reactive<Form>({});

interface FormData{
    city: string[];
    cityCodeList: string[];
    categoryList: string[];
    categoryCodeList: string[];
    action: string;
    actionVal: string;
    time: string;
    timeVal: string;
    projectId: string;
    tagList: object[];
    tags: string[];
    checkedCityData: [];
    customTag: TreeChildModel[];
}

const formData: FormData = reactive({
    city: [],
    cityCodeList: [],
    categoryList: [],
    categoryCodeList: [],
    action: '',
    actionVal: '',
    time: '',
    timeVal: '',
    projectId: '',
    tagList: [],
    tags: [],
    checkedCityData: [],
    checkedCategoryData: [],
    customTag: [],
});

const selectList = ref<TreeChildModel[]>([]);
const selectType = ref(1);
const selectValue = ref('1');

const provinceList = ref<topTagModel[]>([]);
const cityList = ref<topTagModel[]>([]);
const categoryList = ref<topTagModel[]>([]);
const actionList = ref<topTagModel[]>([]);
const timeList = ref<topTagModel[]>([]);
const personList = ref<topTagModel[]>([]);

const typeColumns = computed(() => {
    return actionList.value.map((item: { name: string, id: number }) => {
        return {
            text: item.name,
            value: `${item.id}`,
        };
    });
});

const timeColumns = computed(() => {
    return timeList.value.map((item: { name: string, id: number }) => {
        return {
            text: item.name,
            value: `${item.id}`,
        };
    });
});

const init = async () => {
    formData.projectId = store.state.app.home.projectId as unknown as string;
    const res = await getJcTopTags() as unknown as [];
    res.map((item: topTagModel) => {
        getJcChildTags(item.id).then((res) => {
            if (item.id === 1) {
                personList.value = res;
            } else if (item.id === 2) {
                provinceList.value = res;
                // 设置首页选中城市
                const city = store.state.app.home.selectCity;
                if(city){
                    formData.city = [city.name];
                    const province = provinceList.value.find((item) => {
                        // eslint-disable-next-line max-nested-callbacks
                        return item.children?.find((item) => {
                            return item.tgCode === city.id;
                        });
                    });
                    const checkedCity = province?.children?.find((item) => {
                        return item.tgCode === city.id;
                    });
                    formData.cityCodeList = [`${checkedCity.id}`];
                    formData.checkedCityData = [checkedCity as unknown as TreeChildModel];
                }
            } else if (item.id === 3) {
                categoryList.value = res;
            } else if (item.id === 4) {
                actionList.value = res;
            } else if (item.id === 5) {
                cityList.value = res;
            } else if (item.id === 6) {
                timeList.value = res;
            }
        }).catch((err) => {
            console.log(err);
        });
    });
};

const onCityConfirm = (value: ReturnData)=>{
    formData.checkedCityData = value.checkedData;
    formData.city = value.nameList;
    formData.cityCodeList = value.selected.map((item) => {
        return `${item}`;
    });
};

const onCategoryConfirm = (value: ReturnData) => {
    if (!value.nameList.length) {
        formData.action = '';
        formData.actionVal = '';
        formData.time = '';
        formData.timeVal = '';
    }
    formData.checkedCategoryData = value.checkedData;
    formData.categoryList = value.nameList;
    formData.categoryCodeList = value.selected.map((item) => {
        return `${item}`;
    });
};

const handleClick = (val: Tag[], index: number) => {
    console.log(val, index);
    if(index || index === 0){
        form[index] = val;
    }else{
        if (selectValue.value !== val[0].value) {
            selectValue.value = val[0].value as string;
            formData.cityCodeList = [];
            formData.checkedCityData = [];
            formData.city = [];
        }
        if (val[0].label === '按省市') {
            selectType.value = 1;
            selectList.value = provinceList.value as unknown as TreeChildModel[];
            showCityPicker.value = true;
        } else if (val[0].label === '按城市级别') {
            selectType.value = 2;
            selectList.value = cityList.value as unknown as TreeChildModel[];
            showCityPicker.value = true;
        } else if (val[0].label === '全国') {
            formData.city = ['全国'];
            const cityAllList = provinceList.value.map((item) => {
                return item.children as unknown as TreeChildModel[];
            }).flat(1);
            formData.cityCodeList = cityAllList.map((item:TreeChildModel) => item.id);
            formData.checkedCityData = cityAllList;
        }
        return;
    }
};

const next = async () => {
    if (!formData.city.length) {
        Toast.fail('请选择投放城市');
        return;
    }
    if (!_.isEmpty(form)) {
        formData.tagList = Object.values(form).map((item) => {
            return item;
        }).flat(1);

        const tags: TreeChildModel[] = [];
        Object.keys(form).forEach((key:string)=>{
            const tag = form[key] as unknown as TreeChildModel[];
            tags.push(...tag);
        });
        formData.customTag = tags;
    }

    const formArr = Object.values(form).map((item) => {
        return item.map((item) => {
            return item.id;
        }).join(',');
    });
    formData.tags = [...formArr, formData.cityCodeList.join(','), formData.categoryCodeList.join(','), formData.actionVal, formData.timeVal].filter((item) => {
        return item !== '';
    });
    store.commit('app/setSelectByJd', formData);
    try {
        showLoading();
        await checkTagData({
            tags: formData.tags,
        });
        clearLoading();
        await router.push({
            name: 'productsJdMap'
        });
    } catch (error) {
        console.log(error);
    } finally {
        clearLoading();
    }
};

const pickCategory = () => {
    selectType.value = 3;
    selectList.value = categoryList.value as unknown as TreeChildModel[];
    showCategoryPicker.value = true;
};

const pickType = () => {
    showTypePicker.value = true;
};

const pickTime = () => {
    showTimePicker.value = true;
};

const typeConfirm = (val: { text: string, value: string }) => {
    formData.action = val.text;
    formData.actionVal = val.value;
    showTypePicker.value = false;
};

const timeConfirm = (val: { text: string, value: string }) => {
    formData.time = val.text;
    formData.timeVal = val.value;
    showTimePicker.value = false;
};

const formatCity = (arr: string[]) => {
    if (arr[0] === '全国') {
        return '全国';
    }
    const len = arr.length;
    if (len === 0) {
        return '';
    }
    if (len === 1) {
        return arr[0];
    }
    if (len > 1 && len < 5) {
        const str = arr.slice(0, 4).join('、');
        return str;
    }
    const str = arr.slice(0, 4).join('、');
    return `${str}等${len}个城市`;
};

const formatCategory = (arr: string[]) => {
    const len = arr.length;
    if (len === 0) {
        return '';
    }
    if (len > 0 && len < 3) {
        const str = arr.slice(0, 4).join('、');
        return str;
    }
    const str = arr.slice(0, 2).join('、');
    return `${str}等${len}个类目`;
};

onMounted(async() => {
    await init();
});
</script>

<style lang="scss" scoped>
.page {
    background: #f4f4f4;
    min-height: calc(100vh - 60px);
    display: flex;
    flex-direction: column;
}
.content {
    padding: 0 12px;
    margin-bottom: 110px;
}
.card {
    box-sizing: border-box;
    padding: 16px 12px 4px;
    background: #ffffff;
    border-radius: 10px;
    margin-top: 12px;
}
.title {
    color: #333333;
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
}
.title-bs {
    color: #333333;
    font-size: 14px;
    font-weight: 600;
    margin: 16px 0 6px;
}
.title-sm {
    color: #333333;
    font-size: 14px;
    font-weight: 600;
    margin: 16px 0;
}
.city-label {
    margin-bottom: 12px;
    color: #848484;
    .city-sel {
        color: #333333;
    }
}
.van-cell {
    padding: 15px 0;
    align-items: center;
}
.icon {
    width: 12px;
    height: 12px;
}
:deep([class~="van-cell__title"]) {
    color: #5b5b5b;
}
:deep([class~="van-cell__value"]) {
    color: #333333;
    flex: 2;
}
:deep([class~="van-button"]) {
    background-color: #e60044;
    border: 0;
    border-radius: 6px;
    height: 38px;
}
.footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 6px 12px;
    box-sizing: border-box;
    background: #ffffff;
    box-shadow: 0 -2px 4px 0 #ebebeb80;
    z-index: 1;
}
</style>
